<template>
  <view class="appointment-container">
    <!-- 顶部导航 -->
    <NavigationBar title="我的预约" />

    <!-- 预约列表 -->
    <view class="appointment-content">
      <!-- 加载状态 -->
      <view
        v-if="loading && appointmentList.length === 0"
        class="loading-container"
      >
        <view class="loading-spinner"></view>
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 预约项目列表 -->
      <view v-else-if="appointmentList.length > 0">
        <view
          v-for="(item, index) in appointmentList"
          :key="item.orderId"
          class="card appointment-card flex justify-between p-[30rpx]"
        >
          <view class="w-full">
            <!-- 预约状态和时间 -->
            <view class="w-full flex justify-between items-center mb-[30rpx]">
              <view class="section-title">{{ item.projectName }}</view>
              <view class="status-badge" :class="getStatusClass(item)">
                {{ getStatusText(item) }}
              </view>
            </view>

            <view class="flex justify-between">
              <!-- 预约信息 -->
              <view class="flex flex-col">
                <view class="flex items-center mb-[8rpx]">
                  <text class="text-[26rpx] text-[#121836] font-medium"
                    >项目：</text
                  >
                  <text class="flex-1 text-sm text-[#585766]">{{
                    item.projectName
                  }}</text>
                </view>
                <view class="flex items-center mb-[8rpx]">
                  <text class="text-[26rpx] text-[#121836] font-medium"
                    >医师：</text
                  >
                  <text class="flex-1 text-sm text-[#585766]">{{
                    item.doctorName
                  }}</text>
                </view>
                <view class="flex items-center mb-[8rpx]">
                  <text class="text-[26rpx] text-[#121836] font-medium"
                    >时间：</text
                  >
                  <text class="flex-1 text-sm text-[#585766]">{{
                    item.appointmentDate
                  }}</text>
                </view>
                <view class="flex items-center mb-[8rpx]">
                  <text class="text-[26rpx] text-[#121836] font-medium"
                    >总次数：</text
                  >
                  <text class="flex-1 text-sm text-[#585766]"
                    >{{ item.totalSessions }}次</text
                  >
                </view>
                <view class="flex items-center">
                  <text class="text-[26rpx] text-[#121836] font-medium"
                    >剩余：</text
                  >
                  <text class="flex-1 text-sm text-[#FF5040] font-bold"
                    >{{ item.remainingSessions }}次</text
                  >
                </view>
              </view>

              <!-- 二维码 -->
              <view class="qr-container" @click="showQRCode(item)">
                <QRCode
                  :url="qrCodeUrl || item.qrCodeUrl"
                  :size="96"
                  background="#fff"
                  foreground="#000"
                />
                <text class="qr-hint">点击查看</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else class="empty-state">
        <image
          src="/static/home/common_exam_person.png"
          class="empty-image"
          mode="aspectFit"
        />
        <text class="empty-title">暂无预约记录</text>
        <text class="empty-subtitle">快去预约您喜欢的项目吧～</text>
        <button class="empty-action-btn" @click="goToHome">立即预约</button>
      </view>
    </view>

    <!-- 加载更多 -->
    <view
      v-if="appointmentList.length > 0 && hasMore"
      class="load-more-container"
    >
      <button class="load-more-btn" :disabled="loading" @click="loadMore">
        <view v-if="loading" class="loading-spinner small"></view>
        {{ loading ? "加载中..." : "加载更多" }}
      </button>
    </view>

    <!-- 二维码弹窗 (H5优化版本) -->
    <view v-if="showQRPopup" class="qr-popup-overlay" @click="closeQRPopup">
      <view class="qr-popup-content" @click.stop>
        <view class="qr-popup-header">
          <text class="qr-popup-title">预约二维码</text>
          <view class="qr-popup-close" @click="closeQRPopup">×</view>
        </view>
        <view class="qr-code-container">
          <QRCode
            v-if="currentQRCodeUrl"
            :url="currentQRCodeUrl"
            :size="250"
            background="#fff"
            foreground="#000"
          />
        </view>
        <text class="qr-popup-hint"> 请向工作人员出示此二维码 </text>
        <button class="qr-popup-btn" @click="closeQRPopup">关闭</button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import NavigationBar from "@/components/navigationBar/index.vue";
import QRCode from "@/components/qrCode/index.vue";
import { getMyProjectAppointments } from "@/api/my";
import type { recordResponse } from "@/api/my";
import { getQrCodeUrl } from "@/api";

// 响应式数据
const appointmentList = ref<recordResponse[]>([]);
const loading = ref(false);
const hasMore = ref(true);
const pageNumber = ref(1);
const pageSize = ref(10);
const showQRPopup = ref(false);
const currentQRCodeUrl = ref("");
const qrCodeUrl = ref("");

// 获取预约列表
const getAppointmentList = async (reset = false) => {
  if (loading.value) return;

  loading.value = true;
  try {
    const response = await getMyProjectAppointments({
      pageNumber: reset ? 1 : pageNumber.value,
      pageSize: pageSize.value,
      type: 1,
    });

    if (reset) {
      appointmentList.value = response.data.records;
      pageNumber.value = 1;
    } else {
      appointmentList.value.push(...response.data.records);
    }

    hasMore.value = response.data.records.length === pageSize.value;
    if (!reset) {
      pageNumber.value++;
    }
  } catch (error) {
    console.error("获取预约列表失败", error);
    uni.showToast({
      title: "获取预约列表失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 获取二维码地址
const handleGetQrCodeUrl = async () => {
  try {
    const response = await getQrCodeUrl();
    qrCodeUrl.value = response.data;
  } catch (error) {
    console.error("获取二维码地址失败", error);
    // 使用默认地址
    qrCodeUrl.value = "https://www.baidu.com";
  }
};

// 判断是否是即将到来的预约
const isUpcoming = (item: recordResponse) => {
  const now = new Date();
  const appointmentDateTime = new Date(
    `${item.appointmentDate} ${item.appointmentTime}`,
  );
  return appointmentDateTime > now;
};

// 获取状态样式类
const getStatusClass = (item: recordResponse) => {
  if (isUpcoming(item)) {
    return "status-upcoming";
  } else {
    return "status-completed";
  }
};

// 获取状态文本
const getStatusText = (item: recordResponse) => {
  if (isUpcoming(item)) {
    return "即将到来";
  } else {
    return "已完成";
  }
};

// 显示二维码
const showQRCode = (item: recordResponse) => {
  // 优先使用获取的二维码地址，然后是预约项目的二维码，最后使用默认地址
  currentQRCodeUrl.value =
    qrCodeUrl.value || item.qrCodeUrl || "https://www.baidu.com";
  showQRPopup.value = true;
  // H5环境下阻止页面滚动
  // #ifdef H5
  document.body.style.overflow = "hidden";
  // #endif
};

// 关闭二维码弹窗
const closeQRPopup = () => {
  showQRPopup.value = false;
  // #ifdef H5
  document.body.style.overflow = "auto";
  // #endif
};

// 跳转到首页
const goToHome = () => {
  uni.switchTab({
    url: "/pages/home/index",
  });
};

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    getAppointmentList();
  }
};

// 页面显示时刷新数据

onMounted(async () => {
  await handleGetQrCodeUrl();
  getAppointmentList(true);
});
</script>

<style scoped>
/* H5优化后的样式 */
.appointment-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  font-family:
    -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.appointment-content {
  padding: 20px 15px;
  max-width: 750px;
  margin: 0 auto;
}

/* 统一卡片样式 */
.card {
  margin: 30rpx;
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 调整卡片间距 */
.appointment-content .card {
  margin: 0 0 30rpx 0;
}

/* 统一标题样式 */
.section-title {
  font-size: 32rpx;
  color: #121836;
  font-weight: bold;
  padding-left: 10rpx;
}

/* 预约卡片特殊背景 */
.appointment-card {
  background: linear-gradient(to right, #fdead3, #faefe3) !important;
}

/* 二维码容器样式 */
.qr-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.qr-container:hover {
  transform: scale(1.05);
}

.qr-hint {
  font-size: 20rpx;
  color: #999;
  margin-top: 8rpx;
  text-align: center;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #af6c31;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

.loading-spinner.small {
  width: 16px;
  height: 16px;
  border-width: 2px;
  margin-right: 8px;
  margin-bottom: 0;
}

.loading-text {
  font-size: 14px;
  color: #999;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 状态标签样式 */
.status-badge {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: 500;
}

.status-upcoming {
  background-color: #fff7e6;
  color: #fa8c16;
}

.status-completed {
  background-color: #f0f5ff;
  color: #1890ff;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  margin-top: 40px;
  animation: emptyShow 0.5s ease;
}

@keyframes emptyShow {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.empty-image {
  width: 150px;
  height: 150px;
  opacity: 0.5;
  margin-bottom: 24px;
}

.empty-title {
  font-size: 16px;
  color: #999;
  margin-bottom: 12px;
}

.empty-subtitle {
  font-size: 13px;
  color: #ccc;
  margin-bottom: 24px;
}

.empty-action-btn {
  padding: 12px 32px;
  background: #af6c31;
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.empty-action-btn:hover {
  background: #9a5e2b;
}

/* 加载更多 */
.load-more-container {
  display: flex;
  justify-content: center;
  padding: 24px 0;
}

.load-more-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px 24px;
  background: #f0f0f0;
  color: #666;
  border: none;
  border-radius: 25px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 120px;
}

.load-more-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.load-more-btn:not(:disabled):hover {
  background: #e0e0e0;
}

/* 二维码弹窗 */
.qr-popup-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.qr-popup-content {
  background: white;
  border-radius: 16px;
  padding: 24px;
  max-width: 320px;
  width: 100%;
  text-align: center;
  position: relative;
  animation: popupShow 0.3s ease;
}

@keyframes popupShow {
  from {
    opacity: 0;
    transform: scale(0.8);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.qr-popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.qr-popup-title {
  font-size: 18px;
  font-weight: bold;
  color: #121836;
}

.qr-popup-close {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 16px;
  color: #666;
  transition: background 0.3s ease;
}

.qr-popup-close:hover {
  background: #e0e0e0;
}

.qr-code-container {
  margin: 20px 0;
  display: flex;
  justify-content: center;
}

.qr-popup-hint {
  font-size: 12px;
  color: #666;
  margin: 16px 0;
  line-height: 1.4;
}

.qr-popup-btn {
  width: 100%;
  padding: 12px;
  background: #af6c31;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.qr-popup-btn:hover {
  background: #9a5e2b;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .appointment-content {
    padding: 15px 10px;
  }

  .card {
    margin: 20rpx 10rpx;
  }

  .section-title {
    font-size: 28rpx;
  }

  .status-badge {
    padding: 6rpx 12rpx;
    font-size: 20rpx;
  }

  .qr-hint {
    font-size: 18rpx;
  }

  .empty-state {
    padding: 40px 15px;
    margin-top: 20px;
  }

  .empty-image {
    width: 120px;
    height: 120px;
  }
}

/* H5滚动优化 */
/* #ifdef H5 */
.appointment-container {
  -webkit-overflow-scrolling: touch;
  scroll-behavior: smooth;
}

.appointment-card {
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0.1);
}
/* #endif */
</style>
